<template>
<div>

  <el-cascader v-model="valueList" :options="optionsList" :props="props" collapse-tags clearable filterable>
  </el-cascader>
</div>
</template>

<script>
import {
  GroundController
} from '@/api';
export default {
  props: {
    value: {
      type: String | Number,
      default: ""
    },
    firstOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      //级联选择器
      optionsList: [],
      valueList: this.value ? [this.value] : [],
      props: {
        multiple: false,
        emitPath: false,
        lazyLoad: this.lazyLoads,
        leaf: "leaf",
        lazy: true,
        checkStrictly: true,
        value: 'groundId',
        label: 'groundName',
      },
    };
  },
  updated() {
    this.$emit('update:value', this.valueList.toString());
  },
  watch: {
    value(n, o) {
      this.valueList = n ? [n] : [] ;
    },
  },
  methods: {
    lazyLoads(node, resolve) {
      if (node.level == 0) {
        // 判断是否回显 如果this.valueList>0 代表需要回显，调用formatting 如果不回显直接调取一级数据resolve回去。
        if (this.valueList.length > 0) {
          // 判断是否回显
          this.formatting();
        } else {
          resolve(this.firstOptions);
        }
      } else {
        let list = this.valueList;
        //如果有children 证明有子集可以继续调取
        if (!node.data.children) {
          let params = {
            orgId: node.data.groundId
          };
          GroundController.all(this, params).then(res => {
            if (res.success) {
              resolve(res.data.data.dataList)
            }
          })
        } else {
          resolve([]);
          // return false
        }
        // 先合并在去重
        this.valueList = [...new Set([...this.valueList, ...list])];
      }
    },
    formatting() {
      // 拿一级数据 根据 this.valueList去判断哪些一级数据需要回显
      let res1 = this.firstOptions;
      this.valueList.forEach((item) => {
        if (item.length > 1) {
          item.forEach((sitem, index) => {
            if (index == item.length - 1) {
              return;
            }
            let params = {
              orgId: sitem
            };
            GroundController.all(this, params).then(res => {
              if (res.success) {
                let arr = res.data.data.dataList
                this.findItem(res1, arr, sitem);
              }
            })
          });
        }
      });
    },
    findItem(res, arr, id) {
      for (let i = 0; i < res.length; i++) {
        if (res[i].value === id) {
          res[i].children = arr;
          this.optionsList = res;
        }
        if (res[i].children) {
          this.findItem(res[i].children, arr, id);
        }
      }
    }
  },
  mounted() {

  }
}
</script>

<style>
</style>
